package com.yd.location.module.cms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yd.location.auth.domain.User;
import com.yd.location.auth.service.UserService;
import com.yd.location.common.annotation.TokenInfo;
import com.yd.location.common.cache.RedisKeyEnum;
import com.yd.location.common.cache.RedisUtil;
import com.yd.location.common.spring.base.BaseContent;
import com.yd.location.common.spring.mpbase.IdEntity;
import com.yd.location.common.spring.mpbase.MyEntity;
import com.yd.location.common.spring.pagination.PageRequestDTO;
import com.yd.location.common.web.ParamUtil;
import com.yd.location.common.web.Resp;
import com.yd.location.module.cms.domain.FriendNotice;
import com.yd.location.module.cms.domain.SystemNotice;
import com.yd.location.module.cms.domain.UserSystemNotice;
import com.yd.location.module.cms.service.FriendNoticeService;
import com.yd.location.module.cms.service.SystemNoticeService;
import com.yd.location.module.cms.service.UserSystemNoticeService;
import com.yd.location.module.common.UserEntity;
import com.yd.location.module.location.service.RelationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Created by zk on 2020-07-14 21:24
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/app/notice")
public class AppNoticeController extends BaseContent {
    @Resource
    private SystemNoticeService systemNoticeService;
    @Resource
    private UserSystemNoticeService userSystemNoticeService;
    @Resource
    private FriendNoticeService friendNoticeService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private UserService userService;
    @Resource
    private RelationService relationService;

    /**
     * @author Created by zk on 2020/7/14 22:00
     * @Description 是否存在未读消息
     */
    @GetMapping("/has_unread_notice")
    public Resp hasUnreadNotice(@TokenInfo String id) {
        Integer count;
        //查询是否有未读好友消息
        count = friendNoticeService.lambdaQuery()
                .eq(FriendNotice::getToUserId, id)
                .eq(FriendNotice::getReadFlag, 0)
                .count();
        if (count > 0) {
            return Resp.success(true);
        }
        //查询是否有系统消息
        count = userSystemNoticeService.lambdaQuery()
                .eq(UserEntity::getUserId, id)
                .eq(UserSystemNotice::getReadFlag, 0)
                .count();
        if (count > 0) {
            return Resp.success(true);
        }
        return Resp.success(false);
    }

    /**
     * @author Created by zk on 2020/7/14 21:59
     * @Description 未读消息数 包含好友消息和系统消息
     */
    @GetMapping("/count_unread_notice")
    public Resp countUnreadNotice(@TokenInfo String id) {
        Map<String, Integer> resMap = new HashMap<>(2);
        Integer count;
        //查询未读好友消息数
        count = friendNoticeService.lambdaQuery()
                .eq(FriendNotice::getToUserId, id)
                .eq(FriendNotice::getReadFlag, 0)
                .count();
        resMap.put("friend", count);
        //查询所有系统消息
        count = userSystemNoticeService.lambdaQuery()
                .eq(UserEntity::getUserId, id)
                .eq(UserSystemNotice::getReadFlag, 0)
                .count();
        resMap.put("system", count);
        return Resp.success(resMap);
    }


    /**
     * @author Created by zk on 2020/7/14 21:59
     * @Description 好友消息
     */
    @GetMapping("/friend_notice")
    public Resp friendNotice(@TokenInfo String id, PageRequestDTO pageRequestDTO) {
        if (pageRequestDTO.getPageNumber() < 1) {
            pageRequestDTO.setPageNumber(1);
        }
        if (pageRequestDTO.getPageSize() < 1) {
            pageRequestDTO.setPageSize(10);
        }
        Page<FriendNotice> friendNotices = new Page<>(pageRequestDTO.getPageNumber(), pageRequestDTO.getPageSize(), false);
        QueryWrapper<FriendNotice> wrapper = new QueryWrapper<>();
        wrapper.eq("to_user_id", id).orderByDesc("create_time");
        Page<FriendNotice> page = friendNoticeService.page(friendNotices, wrapper);
        for (FriendNotice friendNotice : page.getRecords()) {
            //将当前页的好友消息改为已读
            if (friendNotice.getReadFlag() == 0) {
                friendNoticeService.lambdaUpdate()
                        .eq(IdEntity::getId, friendNotice.getId())
                        .set(FriendNotice::getReadFlag, 1)
                        .update();
            }
            if(ParamUtil.isBlank(friendNotice.getAvatar())){
                User user = redisUtil.get(RedisKeyEnum.USER, friendNotice.getFromUserId(), () -> userService.getById(friendNotice.getFromUserId()));
                String friendName = relationService.findRelationName(id, friendNotice.getFromUserId());
                friendNotice.setUserName(friendName);
                if (user != null) {
                    friendNotice.setAvatar(user.getAvatar());
                }
            }
        }
        return Resp.success(page);
    }

    /**
     * @author Created by zk on 2020/7/14 21:59
     * @Description 系统消息
     */
    @GetMapping("/system_notice")
    public Resp systemNotice(@TokenInfo String id, PageRequestDTO pageRequestDTO) {
        if (pageRequestDTO.getPageNumber() < 1) {
            pageRequestDTO.setPageNumber(1);
        }
        if (pageRequestDTO.getPageSize() < 1) {
            pageRequestDTO.setPageSize(10);
        }
        Page<UserSystemNotice> userSystemNotices = new Page<>(pageRequestDTO.getPageNumber(), pageRequestDTO.getPageSize(), false);
        QueryWrapper<UserSystemNotice> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id).orderByDesc("create_time");
        Page<UserSystemNotice> page = userSystemNoticeService.page(userSystemNotices, wrapper);
        for (UserSystemNotice userSystemNotice : page.getRecords()) {
            if (userSystemNotice.getReadFlag() == 0) {
                userSystemNoticeService.lambdaUpdate()
                        .eq(IdEntity::getId, userSystemNotice.getId())
                        .set(UserSystemNotice::getReadFlag, 1)
                        .update();
            }
            SystemNotice systemNotice = redisUtil.get(RedisKeyEnum.SYSTEM_NOTICE, userSystemNotice.getSystemNoticeId(), () -> systemNoticeService.getById(userSystemNotice.getSystemNoticeId()));
            userSystemNotice.setName(systemNotice.getName());
            userSystemNotice.setContent(systemNotice.getContent());
        }
        return Resp.success(page);
    }

    /**
     * @author Created by zk on 2020/7/15 16:36
     * @Description 标记已读  type：1-系统消息 2-好友消息
     */
    @GetMapping("/mark_read")
    public Resp markRead(@TokenInfo String id, Integer type) {
        if (type == 1) {
            userSystemNoticeService.lambdaUpdate()
                    .eq(UserEntity::getUserId, id)
                    .eq(UserSystemNotice::getReadFlag, 0)
                    .set(UserSystemNotice::getReadFlag, 1)
                    .update();
            return Resp.success("全部系统消息已读");
        } else if (type == 2) {
            friendNoticeService.lambdaUpdate().eq(FriendNotice::getToUserId, id)
                    .eq(FriendNotice::getReadFlag, 0)
                    .set(FriendNotice::getReadFlag, 1)
                    .update();
            return Resp.success("全部好友消息已读");
        } else {
            return Resp.success("标记已读成功");
        }
    }
}
